package me.leiusual.sharing.util.tool

import android.graphics.Bitmap
import android.graphics.Color
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.common.BitMatrix
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import timber.log.Timber

/**
 * Created by usualm on 2018/5/27
 */
object QRCodeUtils {

  fun createQRCode(text: String, width: Int = 256, height: Int = 256): Bitmap? {
    val hints = mapOf(
        EncodeHintType.CHARACTER_SET to "utf-8",
        EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.M,
        EncodeHintType.MARGIN to 1
    )
    try {
      val bitMatrix = QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints)

      val resMatrix = deleteWhite(bitMatrix)
      val resWidth = resMatrix.width
      val resHeight = resMatrix.height
      Timber.d("%sx%s -> %sx%s", width, height, resWidth, resHeight)

      val pixels = IntArray(resWidth * resHeight)
      for (y in 0 until resHeight) {
        for (x in 0 until resWidth) {
          pixels[y * resWidth + x] = if (resMatrix.get(x, y)) Color.BLACK else Color.WHITE
        }
      }
      return Bitmap.createBitmap(pixels, resWidth, resHeight, Bitmap.Config.RGB_565)
    } catch (e: Exception) {
      Timber.w(e)
    }
    return null
  }

  private fun deleteWhite(bitMatrix: BitMatrix): BitMatrix {
    val rec = bitMatrix.enclosingRectangle
    val resWidth = rec[2]
    val resHeight = rec[3]
    val resMatrix = BitMatrix(resWidth, resHeight)
    for (i in 0 until resWidth) {
      for (j in 0 until resHeight) {
        if (bitMatrix.get(i + rec[0], j + rec[1])) {
          resMatrix.set(i, j)
        }
      }
    }
    return resMatrix
  }
}